'use strict';
import * as vscode from 'vscode';
import * as langclient from 'vscode-languageclient';
import * as fs from "fs";
import * as path from 'path'

export function activate(context: vscode.ExtensionContext) {

    const config = vscode.workspace.getConfiguration('mi-lsp');

    const sourcekit: langclient.Executable = {
        command: process.env.MIROOT + '\\bin\\mic.exe',
        args: ['serve']
    };

    const toolchain = config.get<string>('toolchainPath', '');
    if (toolchain) {
        sourcekit.options = { env: { ...process.env, SOURCEKIT_TOOLCHAIN_PATH: toolchain } };
    }

    const serverOptions: langclient.ServerOptions = sourcekit;

    let clientOptions: langclient.LanguageClientOptions = {
        documentSelector: [
            'mi'
        ],
        synchronize: undefined
    };

    const client = new langclient.LanguageClient('mi-lsp', 'MI Language Server', serverOptions, clientOptions);

    context.subscriptions.push(client.start());

    
    const commandHandler = async (name: string = 'world') => {
        let terminal = vscode.window.activeTerminal
        if(terminal?.name != "MiLang") {
            terminal = vscode.window.createTerminal("MiLang")
        }

        // Check if MIROOT is set 
        const miRoot = process.env.MIROOT
        if (miRoot?.length == 0) {
            vscode.window.showErrorMessage("环境变量 'MIROOT' 未设置");
            return;
        }

        // Get the currently available files 
        const activeEditor = vscode.window.activeTextEditor
        if (!activeEditor) {
            vscode.window.showErrorMessage('没有打开文件');
            return;
        }
        if (activeEditor.document.isUntitled) {
            vscode.window.showErrorMessage('活动文件需要保存后才能运行');
            return;
        }
        if (activeEditor.document.isDirty) {
            activeEditor.document.save();
        }
        if (activeEditor.document.languageId !== 'mi') {
            vscode.window.showErrorMessage('活动文件不是Mi源文件 ');
            return;
        }

        // Get project file 
        const doucmentPath = activeEditor.document.uri.fsPath
        let dir = path.dirname(doucmentPath)
        while (true) {
            let cur = path.join(dir, "项目.mip")
            let isExists = await getStat(cur);
            if (isExists) {
                terminal.sendText("mic build -run \"" + cur + "\"", true)
                terminal.show(true)
                return;
            }

            let curDir = path.dirname(dir)
            if (curDir == dir) {
                break;  
            }

            dir = curDir
        }
        

        vscode.window.showErrorMessage("没有找到 '项目.mip' 文件");
    };

    context.subscriptions.push(vscode.commands.registerCommand('mi.execInTerminal', commandHandler));
    context.subscriptions.push(vscode.commands.registerCommand('mi.execInTerminal-icon', commandHandler));
}

function getStat(path :string){
    return new Promise((resolve, reject) => {
        fs.exists(path, (ok) => {
            resolve(ok);
        })
    })
}


export function deactivate() {
}
